<template>
	<div :class = "['floating-menu', { expanded: isExpanded }]" @click.self = "toggleMenu" ref = "menu">
		<el-button class = "menu-toggle" @click.stop = "toggleMenu" circle>
			<span v-if = "!isExpanded">☰</span>
			<span v-else>×</span>
		</el-button>
		<transition name = "fade">
			<el-menu v-if = "isExpanded" class = "menu-items" :default-active = "activeIndex" mode = "vertical">
				<el-menu-item v-for = "(item, index) in filteredRoutes" :key = "index" :index = "`${index}`"
							  @click = "navigate(item)">
					{{ item.meta?.title || item.name }}
				</el-menu-item>
			</el-menu>
		</transition>
	</div>
</template>

<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import routes from '@/routes'

const router = useRouter()
const route = useRoute()
const menu = ref(null)
const isExpanded = ref(false)

const activeIndex = computed(() => {
	const currentPath = route.path
	for (let i = 0; i < filteredRoutes.value.length; i++) {
		if (filteredRoutes.value[i].path === currentPath) {
			return `${i}`
		}
	}
	return '0' // 默认激活首页
})

// 过滤出有 meta.title 或 name 的路由作为菜单项
const filteredRoutes = computed(() => {
	return routes.filter(route => route.meta?.title || route.name)
})

function toggleMenu() {
	isExpanded.value = !isExpanded.value
}

function navigate(item) {
	router.push(item.path)
	toggleMenu() // 导航后自动关闭菜单
}

onMounted(() => {
	document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
	document.removeEventListener('click', handleClickOutside)
})

function handleClickOutside(event) {
	if (isExpanded.value && menu.value && !menu.value.contains(event.target)) {
		toggleMenu()
	}
}
</script>

<style scoped>
/* 基本样式 */
body {
	font-family: Arial, sans-serif;
}

/* 悬浮菜单样式 */
.floating-menu {
	position: fixed;
	top: 20px;
	right: 20px;
	background-color: #fff;
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	border-radius: 50%;
	width: 40px;
	height: 40px;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: transform 0.3s ease, width 0.3s ease, height 0.3s ease;
	z-index: 1000;
}

.floating-menu.expanded {
	width: 200px;
	height: auto;
	border-radius: 5px;
	transform: translateY(0);
}

.menu-toggle {
	display: block;
	padding: 0;
	background-color: transparent;
	color: #007bff;
	border: none;
	cursor: pointer;
	font-size: 20px;
	line-height: 1;
}

.menu-toggle:hover {
	color: #0056b3;
}

.menu-items {
	list-style-type: none;
	padding: 0;
	margin: 0;
}

.menu-items .el-menu-item {
	padding-left: 20px !important; /* 调整Element Plus默认样式 */
}

/* 动画效果 */
.fade-enter-active, .fade-leave-active {
	transition: opacity 0.3s;
}

.fade-enter, .fade-leave-to /* .fade-leave-active 在低于版本 2.1.8 中 */
{
	opacity: 0;
}
</style>